package cn.liuhuan1.blogsModel.filter;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: liuhuan
 * @Date: 2021/2/20 - 02 - 20 - 12:55
 * @Description:
 * @version: 1.0
 */
@Component
@Order(1)
@WebFilter(filterName = "firstFilter",urlPatterns = "/*")
public class RequestFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器 开始");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse rep, FilterChain chain) throws IOException, ServletException {
        System.out.println("过滤器 工作间");
        HttpServletResponse response = (HttpServletResponse) rep;
        HttpServletRequest request = (HttpServletRequest) req;

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE,x-requested-with,Authorization");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        String method = request.getMethod();
        if(method.equalsIgnoreCase("OPTIONS")){
            response.getOutputStream().write("Success".getBytes("utf-8"));
        }else{
            chain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {
        System.out.println("过滤器 结束");
    }
}
